package com.example.shop_2304.login

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.method.PasswordTransformationMethod
import android.text.method.TransformationMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.shop_2304.MainActivity
import com.example.shop_2304.R
import com.example.shop_2304.databinding.ActivityLoginBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    override fun initView() {


        //点击获取验证码---短信（通知），10秒倒计时
        binding.codeSend.setOnClickListener {
            //不为空
            val etUsername = binding.etUsername.text.toString()
            if(etUsername.isEmpty()){
                ToastUtils.showLong("用户名不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileExact(etUsername)){
                ToastUtils.showLong("用户名格式不正确，应该为手机号")
                return@setOnClickListener
            }
            viewModel.codeSend(etUsername)
        }
        //点击登录按钮，实现登录功能
        binding.btnLogin.setOnClickListener {
            //判断非空
            val etUsername = binding.etUsername.text.toString()
            val etCode = binding.etCode.text.toString()
            if(etUsername.isEmpty()||etCode.isEmpty()){
                ToastUtils.showLong("用户名和验证码均不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileExact(etUsername)){
                ToastUtils.showLong("用户名格式不正确，应该为手机号")
                return@setOnClickListener
            }
            if(!binding.cb.isChecked){
                ToastUtils.showLong("请先勾选用户协议")
                return@setOnClickListener
            }
            viewModel.loginCode(etCode,etUsername)
        }
        //富文本
        val spannableStringBuilder = SpannableStringBuilder(binding.fwb.text.toString())
        val clickableSpan = object:ClickableSpan(){
            override fun onClick(widget: View) {
                //跳转webView界面
                //ARouter.getInstance().build("/app/WebViewActivity").withString("url","http://www.baidu.com").navigation()
                //binding.cb.isChecked = true
                //弹对话框
                showAlert("这是用户协议")
            }
        }
        val clickableSpan2 = object:ClickableSpan(){
            override fun onClick(widget: View) {
                //ARouter.getInstance().build("/app/WebViewActivity").withString("url","http://www.sina.com").navigation()
                //binding.cb.isChecked = true
                showAlert("这是隐私政策")
            }
        }
        spannableStringBuilder.setSpan(clickableSpan,7,13,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        spannableStringBuilder.setSpan(clickableSpan2,14,20,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        binding.fwb.movementMethod = LinkMovementMethod.getInstance()
        binding.fwb.text = spannableStringBuilder
    }

    private fun showAlert(s: String) {
        AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage(s)
            .setNegativeButton("取消"){
                dialog,which->
                binding.cb.isChecked = false
            }
            .setPositiveButton("同意",object:DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    binding.cb.isChecked = true
                }
            })
            .show()
    }

    override fun initData() {
        viewModel.codeSendSuccess.observe(this){
            if(it.code==200){
                //发送通知//不同的版本发送通知
                //通知管理器
                val manager =
                    getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.O){
                    //高版本通知
                    val notificationChannel = NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT)
                    val notification = Notification.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("验证码")
                        .setContentText("登录验证码:${it.data.content.substring(8,14)}")
                        .setChannelId("id")
                        .build()
                    manager.createNotificationChannel(notificationChannel)
                    manager.notify(1,notification)
                }else{
                    //低版本
                    val notification = Notification.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("验证码")
                        .setContentText("登录验证码:${it.data.content.substring(8,14)}")
                        .build()
                    manager.notify(1,notification)
                }
                //开始倒计时
                binding.codeSend.isEnabled = false
                lifecycleScope.launch {
                    for (i in 10 downTo 1){
                        binding.codeSend.text = "${i}秒后再次获取"
                        delay(1000)
                    }
                    binding.codeSend.text = "获取验证码"
                    binding.codeSend.isEnabled = true
                }
            }
        }

        viewModel.loginCodeSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                SPUtils.getInstance().put("phone",it.data.phone)
                //跳转到主页面
                startActivity(Intent(this,MainActivity::class.java))
            }
        }
    }

    override fun getViewModel(): Class<LoginViewModel>  = LoginViewModel::class.java

    override fun getLayout(): Int = R.layout.activity_login

}

class AsteriskTransformationMethod : TransformationMethod {
    override fun getTransformation(source: CharSequence, view: View): CharSequence {
        return if (source.length >= 3) {
            // 显示前 3 位，其余用 * 代替
            "${source.subSequence(0, 3)}${"*".repeat(source.length - 3)}"
        } else {
            source
        }
    }

    override fun onFocusChanged(
        view: View?,
        sourceText: CharSequence?,
        focused: Boolean,
        direction: Int,
        previouslyFocusedRect: Rect?
    ) {
        // 不需要处理
    }
}